<template>
  <van-form @submit="onSubmit">
    <van-cell-group inset>
      <van-field
          v-model="userAccount"
          name="userAccount"
          label="邮箱"
          placeholder="请填写邮箱"
      >
        <template #left-icon>
          <svg
              style="margin-top: 3px"
              t="1722673029650" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="3716" width="18" height="18">
            <path d="M256 384c-12.8 57.6-6.4 115.2 6.4 166.4 12.8 44.8-6.4 89.6-44.8 115.2-57.6 32-128-12.8-134.4-70.4-57.6-300.8 211.2-576 518.4-518.4C422.4 96 288 217.6 256 384z" fill="#FFDC04" p-id="3717"></path><path d="M531.2 800c51.2-19.2 102.4-51.2 140.8-89.6 32-32 83.2-38.4 121.6-12.8 57.6 32 57.6 115.2 6.4 153.6-230.4 198.4-601.6 102.4-704-192C192 800 371.2 851.2 531.2 800z" fill="#E03A22" p-id="3718"></path><path d="M755.2 352c-44.8-38.4-96-64-147.2-76.8-44.8-12.8-76.8-51.2-76.8-96 0-64 70.4-108.8 128-83.2 288 102.4 390.4 467.2 185.6 704 76.8-153.6 32-339.2-89.6-448z" fill="#27AA3A" p-id="3719"></path><path d="M633.6 492.8c0-12.8 0-25.6-6.4-32 0-6.4 0-6.4-6.4-12.8 0-64-38.4-115.2-108.8-115.2S403.2 384 403.2 448c0 6.4-6.4 6.4-6.4 12.8-6.4 12.8-6.4 19.2-6.4 25.6v6.4c-12.8 6.4-25.6 25.6-32 44.8-12.8 32-12.8 64-6.4 64 6.4 6.4 19.2-6.4 32-19.2 0 19.2 12.8 38.4 25.6 51.2-12.8 0-25.6 12.8-25.6 25.6 0 19.2 25.6 32 64 32 32 0 57.6-12.8 64-25.6h6.4c6.4 12.8 32 25.6 64 25.6s64-12.8 64-32c0-12.8-12.8-19.2-25.6-25.6 12.8-12.8 25.6-25.6 32-44.8 12.8 19.2 25.6 25.6 32 19.2 12.8-6.4 6.4-32-6.4-64-19.2-32-32-44.8-44.8-51.2z" fill="#038BC5" p-id="3720"></path></svg>
        </template>
      </van-field>

      <van-field
          v-model="userCode"
          center
          type="digit"
          left-icon="setting"
          name="userCode"
          label="验证码"
          placeholder="请填写验证码"
      >
        <template #button>
          <van-button v-if="!countdown" @click="sendCode" size="small" type="primary">发送验证码</van-button>
          <van-button v-else size="small">{{ remainingTime }}s</van-button>
        </template>
      </van-field>
    </van-cell-group>

    <div>ip:{{ip}}</div>

    <div style="
    color: #1677ff;
    font-size: 16px;
    margin-right: 32px;
    display: flex;
    justify-content: flex-end;
    ">
      <span @click="toRegister">注册</span>
    </div>

    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        登录
      </van-button>
    </div>

  </van-form>
</template>


<script setup lang="ts">
import {onMounted, ref} from "vue";
import {useRoute, useRouter} from "vue-router";
import {loginEmail} from "../../api/userApi.ts";
import {showToast} from "vant";
import {sendEmail} from "../../api/emailApi.ts";
import {userStore} from "../../stores/user/user.ts";
import {initConnection} from "../../ws/socketWork.ts";

const userAccount = ref('');
const userCode = ref('');
const router = useRouter();
const route = useRoute();
const countdown = ref(false);
const remainingTime = ref(60);
const userStoreAPI = userStore();//当前用户存储
const ip = ref('');

console.log("redirect",route.query?.redirect);


const onSubmit = async () => {
  //校验参数
  if (userAccount.value.length != 17 || !userAccount.value.includes('@qq.com')){
    showToast("邮箱不正确");
    return;
  }

  if (userCode.value == ''){
    showToast("请填写验证码");
    return;
  }

  const data = {
    email: userAccount.value,
    code: userCode.value
  };
  const res = await loginEmail(data);
  console.log("res",res);
  // 兼容新格式 code: 0 和旧格式 code: 200
  if (res.code === 0 || res.code === 200){
    // 新格式：res.data.user，旧格式：res.data
    const userData = res.data?.user || res.data;
    //缓存用户信息
    userStoreAPI.setCurrentUser(userData);

    //判断是否是新注册的用户(是否选择了标签)
    if (userData.userStatus == 1){
      //跳转到选择标签页面
      router.push('/genderSelect');

    }else{
      //直接重定向
      const redirectUrl = route.query?.redirect ?? '/index';//如果没有就默认时index首页
      if (redirectUrl === '/index') {
        router.replace('/index');
      } else {//redirectUrl == 'http://localhost:5173/user'
        if (typeof redirectUrl === "string") {
          window.location.href = redirectUrl + "";
        }
      }
    }

    //进行创建连接ws
    // initConnection();
    self.postMessage(`{"type":"initWS","value":${userData.id}}`);
  }else {
    showToast(res?.message != '' ? "登录失败" : res?.message);
  }
};


//跳转到注册页面
const toRegister = ()=>{
  router.push('/register');
}

//发送验证码方法
const sendCode = ()=>{
  //不能一直发送
  if (remainingTime.value!=60){
    return;
  }

  //校验
  if (userAccount.value == ''){
    showToast("请填写邮箱");
    return;
  }
  if (!userAccount.value.includes('@qq.com') || userAccount.value.length != 17){
    showToast("邮箱不正确");
    return;
  }

  //用发送邮箱验证码
  sendEmail(userAccount.value).then(res =>{
    console.log("res",res);
    if (200 == res.code){//成功
      showToast("验证码已发送");
      countdown.value = true;
      const timer = setInterval(() => {
        if (remainingTime.value > 0) {
          remainingTime.value--;
        } else {
          clearInterval(timer);
          countdown.value = false;
          remainingTime.value = 60;
        }
      }, 1000);
    }else {//失败
      showToast(res.data?.message);
    }
  }).catch(err => {
    showToast("错误");
  });
};


</script>



<style scoped>

</style>